<template>
  <div>
    <div class="search">
      <input
        type="text"
        name="text"
        class="input"
        placeholder="搜索文章标题关键字"
        ref="searchIpt"
        @input="handleSearch"
        v-model="searchTitle"
      />
    </div>
    <div class="articleList">
      <ArticleList :articleWhere="articleWhere"> </ArticleList>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive, defineAsyncComponent } from 'vue'

const ArticleList = defineAsyncComponent(
  () => import('@/components/article/ArticleList.vue')
)
// 导入文章列表
const searchTitle = ref('')
// 获取文章输入的焦点
const searchIpt = ref<HTMLInputElement>()
onMounted(() => {
  searchIpt.value && searchIpt.value.focus()
})
const articleWhere = reactive({
  title: '',
})

let timer: null | NodeJS.Timeout = null
// 搜索防抖
const handleSearch = () => {
  timer && clearTimeout(timer)
  // 这个清除定时器一定要放在这个之前 不然会剩一个定时器
  if (!searchTitle.value.trim()) return
  timer = setTimeout(() => {
    // 改变搜索值
    articleWhere.title = searchTitle.value.trim()
  }, 1000)
}
</script>

<style scoped lang="scss">
.search {
  position: relative;
  width: 70%;
  margin: 0 auto;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: -100px;
}

/* From uiverse.io by @Galahhad */
.input {
  top: -50px;
  left: 0;
  background-color: #383838;
  border: 2px solid none;
  border-top-width: 1.7em;
  margin: 0;
  padding: 0;
  color: #383838;
  word-wrap: break-word;
  outline: 7px solid #383838;
  height: 30px;
  font-size: 17px;
  text-align: center;
  transition: all 1s;
  flex: 1;
  font-weight: bold;
  font-family: 'Courier New', Courier, monospace;
}

.input:hover {
  border-top-width: 0.2em;
  background-color: #f1e8e8;
}

.input:focus {
  border-top-width: 0.2em;
  background-color: #f1e8e8;
}

.articleList {
  margin: 100px auto 0;
  width: 65%;
  min-height: calc(100vh - 435px);
}

@media (max-width: 760px) {
  .search {
    margin-top: -50px;
  }

  .articleList {
    margin: 50px auto 0;
    width: 92%;
    min-height: calc(100vh - 235px);
  }

  .search {
    width: 92%;

    button {
      font-size: 12px;
      padding: 3px 5px;
    }

    .input {
      font-size: 14px;
      height: 25px;
    }
  }
}
</style>
